//
// Created by gastonfeng on 2022/9/20.
//
#ifdef ARDUINO_ARCH_STM32

#include <stm32_def.h>
#include "nSPI.h"

#ifndef ARDUINO
using spi_status_e = enum {
    SPI_OK = 0,
    SPI_TIMEOUT = 1,
    SPI_ERROR = 2
};
#endif
extern "C"
{
#include "utility/spi_com.h"
}

nSPI::nSPI(PinName MOSI, PinName MISO, PinName SCK, PinName ssel) {
    _spi.pin_miso = (MISO);
    _spi.pin_mosi = (MOSI);
    _spi.pin_sclk = (SCK);
    _spi.pin_ssel = NC;
}

void nSPI::begin(PinName _pin) {
    spi_init(&_spi, SPI_SPEED_CLOCK_DEFAULT, SPI_MODE_0, MSBFIRST);
    transfer(_pin, 0xff);
    transfer(_pin, 0xff);
    transfer(_pin, 0xff);
    transfer(_pin, 0xff);
    transfer(_pin, 0xff);
    transfer(_pin, 0xff);
    transfer(_pin, 0xff);
}

void nSPI::end() {
}

void nSPI::beginTransaction(PinName _pin, SPISettings settings) {

    if ((_pin != NC) && (_spi.pin_ssel == NC)) {
        pin_function(_pin, STM_PIN_DATA(STM_MODE_OUTPUT_PP, GPIO_NOPULL, 0));
        digitalWriteFast(_pin, HIGH);
    }
}

void nSPI::endTransaction(PinName pin) {
}

nSPI::nSPI(SPI_TypeDef *pDef) {
    _spi.spi = pDef;
}

void nSPI::transfer(PinName pin, void *_buf, size_t _count, SPITransferMode _mode) {
    transfer(pin, (uint8_t *) _buf, (uint8_t *) _buf, _count, _mode);
}


nSPI::nSPI() = default;

#endif
